package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.CabinetFileService;
import com.xbongbong.paas.data.service.SerialNoService;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.lowcode.LowCodeExecuteHelp;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.StartProcessDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.StartProcessVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.dynamic.help.DynamicHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.pojo.AddValidateReturnPojo;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.SaveFormExplainPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.process.operate.ProcessFieldHelp;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderSubDataEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.help.AnalyticalHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderSubDataModel;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.workorder.abstracts.AbstractWorkOrderAddDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/02/26 14:02
 */
@Service("workOrderDataFormDataServiceImpl")
public class WorkOrderDataFormDataServiceImpl extends AbstractWorkOrderAddDataService {

    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderDataFormDataServiceImpl.class);

    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private CabinetFileService cabinetFileService;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private UserHelp userHelp;
    @Resource
    private ProcessFieldHelp processFieldHelp;
    @Resource
    private DynamicHelp dynamicHelp;
    @Resource
    private LowCodeExecuteHelp lowCodeExecuteHelp;
    @Resource
    private AnalyticalHelp analyticalHelp;
    @Resource
    private SerialNoService serialNoService;
    @Resource
    private WorkOrderSubDataModel workOrderSubDataModel;

    @Override
    public List<Integer> businessList() {
        return Arrays.asList(XbbRefTypeEnum.WORK_ORDER.getCode());
    }

    @Override
    public BeforeSaveVO beforeSave(FormDataAddDTO formDataAddDTO) throws XbbException {
        BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
        try {
            String corpid = formDataAddDTO.getCorpid();
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formDataAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            String userId = formDataAddDTO.getUserId();
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formDataAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplainEntity.getExplains(), null);
            if (Objects.nonNull(explainMap.get(FieldTypeEnum.SERIALNO.getAlias())) && StringUtil.isEmpty(formDataAddDTO.getGroupNumber())) {
                String serialNo = getSerialNo(formDataAddDTO, corpid, explainMap.get(FieldTypeEnum.SERIALNO.getAlias()));
                formDataAddDTO.setSerialNo(serialNo);
            }
            ValidateDataDTO validateDataDTO = new ValidateDataDTO();
            BeanUtil.copyProperties(formDataAddDTO, validateDataDTO);
            JSONObject dataObj = formDataAddDTO.getDataList();

            //过滤data中null的数据
            String explainList1 = workOrderExplainEntity.getExplains();
            List<FieldAttrEntity> fieldList = JSONArray.parseArray(explainList1, FieldAttrEntity.class);
            //过滤data中数据为null的情况
            for (FieldAttrEntity fieldAttrEntity : fieldList) {
                String key = fieldAttrEntity.getAttr();
                Boolean isEmpty = (Objects.isNull(dataObj.get(key)));
                if (isEmpty) {
                    dataObj.remove(key);
                    continue;
                }
            }
            //初始化一个评价星级,统计要用,存在es
            dataObj.put(WorkOrderEnum.RATE_STAR.getAttr(), 0);
            formDataAddDTO.setDataList(dataObj);
            // 判断是否开启了流程
            explainMap =  processFieldHelp.processSetVisible(workOrderFormEntityExt.getIsProcessForm(),  workOrderFormEntityExt.getId(), workOrderFormEntityExt.getAppId(), formDataAddDTO, explainMap);

            validateDataDTO.setData(formDataAddDTO.getDataList());
            validateDataDTO.setExplainMap(explainMap);
            //工单参数校验
            ProSaveHelp.analyticalData(validateDataDTO);
            //基本参数校验
            formDataValidateDataHelp.validateData(validateDataDTO);
            saasSaveHelp.beforeSave(validateDataDTO);
            formDataAddDTO.setSaasNeedRedundantAttrPoJo(validateDataDTO.getSaasNeedRedundantAttrPoJo());
            WorkOrderEntity workOrderEntity = new WorkOrderEntity();
            BeanUtil.copyProperties(formDataAddDTO, workOrderEntity);
            String ownerId = formDataAddDTO.getUserId();
            workOrderEntity.setOwnerId(ownerId);
            if (Objects.nonNull(formDataAddDTO.getOwnerId()) && !formDataAddDTO.getOwnerId().isEmpty()) {
                workOrderEntity.setOwnerId(Objects.toString(formDataAddDTO.getOwnerId().get(0).getId(), ""));
            }
            workOrderEntity.setData(formDataAddDTO.getDataList());
            workOrderEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            workOrderEntity.setSerialNo(formDataAddDTO.getSerialNo());
            // 所属部门的id，由前端传入
            workOrderEntity.setDepartmentId(validateDataDTO.getDepartmentId());
            formDataAddDTO.setDepartmentId(validateDataDTO.getDepartmentId());

            //根据form拿到templateId
            workOrderEntity.setTemplateId(workOrderFormEntityExt.getTemplateId());
            workOrderEntity.setMenuId(workOrderFormEntityExt.getMenuId());
            workOrderEntity.setCreatorId(userId);
            //不走工作流，保存
            workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());

            beforeSaveVO.setExplainMap(explainMap);
            beforeSaveVO.setExplainList(fieldList);
            beforeSaveVO.setSaasNeedRedundantAttrPojo(validateDataDTO.getSaasNeedRedundantAttrPoJo());
            beforeSaveVO.setWorkOrderFormEntityExt(workOrderFormEntityExt);
            beforeSaveVO.setWorkOrderEntity(workOrderEntity);

            //是否启用新工作流
            if (isEnableNewWorkflow(formDataAddDTO, beforeSaveVO, workOrderEntity)) {
                if (!formDataAddDTO.getIsSatisfyTrigger()) {
                    // 无需走工作流
                    beforeSaveVO.getWorkOrderEntity().setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
                }
                return beforeSaveVO;
            }
    
            Integer noApprovalRequired = startProcess(workOrderFormEntityExt, formDataAddDTO, userId, workOrderEntity);

            beforeSaveVO.setNoApprovalRequired(noApprovalRequired);
            return beforeSaveVO;
        }catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("insertWorkOrderFormDataServiceImpl.beforeSave 出错",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    
    @Override
    public void afterSaveLog(FormDataAddDTO formDataAddDTO, WorkOrderFormEntityExt workOrderFormEntityExt, WorkOrderEntity workOrderEntity, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        boolean isImport = Objects.equals(1, formDataAddDTO.getIsImport());
        if (isImport) {
            return;
        }
        String serialNo = workOrderEntity.getSerialNo();
        saveLogger(formDataAddDTO, workOrderEntity, serialNo, XbbRefTypeEnum.WORK_ORDER.getName(), OperateModuleTypeEnum.WORK, saveVO, beforeSaveVO);
    }

    @Override
    public SaveVO save(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, WorkOrderFormEntityExt paasFormEntity, WorkOrderEntity paasFormDataEntity) throws XbbException {
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            WorkOrderEntity workOrderEntity = beforeSaveVO.getWorkOrderEntity();
            UserVO userVO = userHelp.getUserName(corpid, formDataAddDTO.getUserId(), formDataAddDTO.getLoginUserName(), workOrderEntity.getFlowStatus(), workOrderEntity.getCreatorId());

            if (Objects.equals(1, beforeSaveVO.getNoApprovalRequired())) {
                // 工单data中移除负责人和协同人
                JSONObject conProductDataList = workOrderEntity.getData();

                FormDataUtil.removeSystemData(conProductDataList);
                Object richTextData = removeRichText(conProductDataList);
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conProductDataList, WorkOrderEnum.SPARE_PARTS.getAttr());
                workOrderEntity.setData(conProductDataList);
                workOrderModel.insert(workOrderEntity);
                dataId = workOrderEntity.getId();
                conProductDataList.put(WorkOrderEnum.SPARE_PARTS.getAttr(), productArray);
                JSONObject subForm = workOrderEntity.getSubFormData() == null ? new JSONObject(): workOrderEntity.getSubFormData();
                workOrderEntity.getData().putAll(subForm);
                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(beforeSaveVO.getExplainMap(), conProductDataList, workOrderEntity.getSubFormData(), formDataAddDTO.getCorpid(), dataId, XbbRefTypeEnum.WORK_ORDER.getCode(), userVO.getUserId());
                //富文本数据保存
                saveRichText(formDataAddDTO, workOrderEntity, richTextData);
            }
            return new SaveVO(beforeSaveVO.getNoApprovalRequired(), dataId, userVO, workOrderEntity );
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    @Override
    public FormDataAddVO afterSave(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, WorkOrderFormEntityExt workOrderFormEntityExt, WorkOrderEntity workOrderEntity) throws XbbException {
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            FormDataAddVO formDataAddVO = new FormDataAddVO();
            if (Objects.equals(1, beforeSaveVO.getNoApprovalRequired())) {
                // log
                afterSaveLog(formDataAddDTO, workOrderFormEntityExt, workOrderEntity, saveVO, beforeSaveVO);
                JSONObject workOrderDataObj = workOrderEntity.getData();
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                saasFormSaveDTO.setIsNew(true);
                saasFormSaveDTO.setOldData(workOrderDataObj);
                saasFormSaveDTO.setNewData(workOrderDataObj);
                saasFormSaveDTO.setOldWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setNewWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
                workOrderService.afterSave(saasFormSaveDTO);
                // api
                apiHook(formDataAddDTO, saveVO, beforeSaveVO);

                // 动态处理
                dynamicHelp.addLinkData(saasFormSaveDTO);
                // 业务规则
                PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
                BeanUtil.copyProperties(beforeSaveVO.getWorkOrderFormEntityExt(), paasFormEntityExt);
                activeRule(formDataAddDTO, beforeSaveVO, workOrderEntity, paasFormEntityExt);

                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setDataId(saveVO.getDataId());
                formDataAddVO.setFormDataId(saveVO.getDataId());
            }else {
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            return formDataAddVO;
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    private Integer startProcess(WorkOrderFormEntityExt workOrderFormEntityExt, FormDataAddDTO formDataAddDTO, String userId, WorkOrderEntity workOrderEntity) throws XbbException {
        // 是否往form_data表中插入数据
        Integer noApprovalRequired = 1;
        if (Objects.equals(1, workOrderFormEntityExt.getIsProcessForm())) {
            StartProcessDTO startProcessDTO = new StartProcessDTO();
            BeanUtil.copyProperties(formDataAddDTO, startProcessDTO);
            startProcessDTO.setOwnerId(workOrderEntity.getOwnerId());
            startProcessDTO.setData(formDataAddDTO.getDataList());
            startProcessDTO.setDepartmentId(workOrderEntity.getDepartmentId());
            startProcessDTO.setCreatorId(userId);

            StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
            if (Objects.isNull(startProcessVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
            }
            noApprovalRequired = startProcessVO.getNoApprovalRequired();
        }
        return noApprovalRequired;
    }
    /**
     * 开启严控模式后，生成相应的流水号
     * @param formDataSaveDTO
     * @param corpid
     * @param fieldAttrEntity
     * @throws XbbException
     */
    public String getSerialNo(FormDataAddDTO formDataSaveDTO, String corpid, FieldAttrEntity fieldAttrEntity) throws XbbException {
        return serialNoService.getSerialNo(formDataSaveDTO, corpid, fieldAttrEntity);
    }

    @Override
    public void apiHook(FormDataAddDTO formDataAddDTO, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        lowCodeExecuteService(formDataAddDTO, saveVO, beforeSaveVO);
    }

    /**
     * 低代码执行服务
     * @param formDataAddDTO
     * @param saveVO
     * @param beforeSaveVO
     * @throws XbbException
     */
    @Override
    public void lowCodeExecuteService(FormDataAddDTO formDataAddDTO, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        try {
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(saveVO.getWorkOrderEntity(), paasFormDataEntity);
            saveVO.setPaasFormDataEntity(paasFormDataEntity);
            lowCodeExecuteHelp.lowCodeExecuteService(formDataAddDTO, saveVO, beforeSaveVO);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.impl.workOrderDataFormDataServiceImpl.lowCodeExecuteService fail", e);
        }

    }

    @Override
    public SaveVO saveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, WorkOrderFormEntityExt workOrderFormEntityExt, WorkOrderEntity workOrderEntity) throws XbbException {
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            UserVO userVO = userHelp.getUserName(corpid, formDataAddDTO.getUserId(), formDataAddDTO.getLoginUserName(), workOrderEntity.getFlowStatus(), workOrderEntity.getCreatorId());

            // 工单data中移除负责人和协同人
            JSONObject conProductDataList = workOrderEntity.getData();

            Object richTextData = removeRichText(conProductDataList);
            JSONObject originData = (JSONObject) conProductDataList.clone();

            FormDataUtil.removeSystemData(conProductDataList);
            JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conProductDataList, WorkOrderEnum.SPARE_PARTS.getAttr());
            workOrderEntity.setData(conProductDataList);
            workOrderModel.insert(workOrderEntity);
            dataId = workOrderEntity.getId();
            conProductDataList.put(WorkOrderEnum.SPARE_PARTS.getAttr(), productArray);
            JSONObject subForm = workOrderEntity.getSubFormData() == null ? new JSONObject(): workOrderEntity.getSubFormData();
            workOrderEntity.getData().putAll(subForm);
            //文件柜数据保存
//            cabinetFileService.saveDataCabinetFile(beforeSaveVO.getExplainMap(), conProductDataList, workOrderEntity.getSubFormData(), formDataAddDTO.getCorpid(), dataId, XbbRefTypeEnum.WORK_ORDER.getCode(), userVO.getUserId());

            //富文本数据保存
            saveRichText(formDataAddDTO, workOrderEntity, richTextData);
            originData.put(WorkOrderEnum.SPARE_PARTS.getAttr(), productArray);
            workOrderEntity.setData(originData);
            return new SaveVO(beforeSaveVO.getNoApprovalRequired(), dataId, userVO, workOrderEntity);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    @Override
    public FormDataAddVO afterSaveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, WorkOrderFormEntityExt workOrderFormEntityExt, WorkOrderEntity workOrderEntity) throws XbbException {
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            FormDataAddVO formDataAddVO = new FormDataAddVO();
            // log
//            afterSaveLog(formDataAddDTO, new PaasFormDataEntity(), saveVO, beforeSaveVO);
            JSONObject workOrderDataObj = workOrderEntity.getData();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            saasFormSaveDTO.setIsNew(true);
            saasFormSaveDTO.setOldData(workOrderDataObj);
            saasFormSaveDTO.setNewData(workOrderDataObj);
            saasFormSaveDTO.setOldWorkOrderEntity(workOrderEntity);
            saasFormSaveDTO.setNewWorkOrderEntity(workOrderEntity);
            saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
            workOrderService.afterSaveForWorkFlow(saasFormSaveDTO);
            // api
//            apiHook(formDataAddDTO, saveVO, beforeSaveVO);


            // 业务规则
//            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
//            BeanUtil.copyProperties(beforeSaveVO.getWorkOrderFormEntityExt(), paasFormEntityExt);
//            activeRule(formDataAddDTO, beforeSaveVO, workOrderEntity, paasFormEntityExt);

            formDataAddVO.setDataId(saveVO.getDataId());
            formDataAddVO.setFormDataId(saveVO.getDataId());
            formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            return formDataAddVO;
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    @Override
    public void validatePermission(FormDataAddDTO formDataAddDTO) throws XbbException {

    }

    @Override
    public WorkOrderFormEntityExt getFormEntity(FormDataAddDTO formDataAddDTO) throws XbbException {
        WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
        if ( Objects.isNull(workOrderFormEntityExt) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        return workOrderFormEntityExt;
    }

    @Override
    public SaveFormExplainPojo getExplainMap(Long formId, String corpid) throws XbbException {
        WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
        if (Objects.isNull(workOrderExplainEntity) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSON.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(explainList, null);
        SaveFormExplainPojo saveFormExplainPojo = new SaveFormExplainPojo();
        saveFormExplainPojo.setExplainList(explainList);
        saveFormExplainPojo.setExplainMap(explainMap);
        return saveFormExplainPojo;
    }

    @Override
    public AddValidateReturnPojo analyticalData(FormDataAddDTO formDataAddDTO, ValidateDataDTO validateDataDTO, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        // 校验必填字段
        //初始化一个评价星级,统计要用,存在es
        validateDataDTO.getData().put(WorkOrderEnum.RATE_STAR.getAttr(), 0);
        ProSaveHelp.analyticalData(validateDataDTO);
        formDataValidateDataHelp.validateData(validateDataDTO);
        // 校验各个业务的逻辑
        // TODO 不懂为啥标签要在saasSaveHelp.beforeSave里解析，为什么不放在ProSaveHelp.analyticalData
//        SaveFormatHelp.dealLabelData(validateDataDTO.getData(), explainMap);
        analyticalHelp.beforeSave(validateDataDTO);
        return new AddValidateReturnPojo();
    }

    @Override
    public WorkOrderEntity getFormData(FormDataAddDTO formDataAddDTO, WorkOrderFormEntityExt paasFormEntityExt, Map<String, FieldAttrEntity> explainMap, Long department, JSONObject data) throws XbbException {
        WorkOrderEntity workOrderEntity = new WorkOrderEntity();
        String ownerId = formDataAddDTO.getUserId();
        workOrderEntity.setOwnerId(ownerId);
        if (Objects.nonNull(formDataAddDTO.getOwnerId()) && !formDataAddDTO.getOwnerId().isEmpty()) {
            workOrderEntity.setOwnerId(Objects.toString(formDataAddDTO.getOwnerId().get(0).getId(), ""));
        }
        workOrderEntity.setData(formDataAddDTO.getDataList());
        workOrderEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
        String serialNo = serialNoService.getSerialNo(formDataAddDTO, formDataAddDTO.getCorpid(), explainMap.get(FieldTypeEnum.SERIALNO.getAlias()));
        workOrderEntity.setSerialNo(serialNo);
        workOrderEntity.setCorpid(formDataAddDTO.getCorpid());
        workOrderEntity.setAppId(paasFormEntityExt.getAppId());
        workOrderEntity.setFormId(paasFormEntityExt.getId());
        // 所属部门的id，由前端传入
        workOrderEntity.setDepartmentId(department);

        //根据form拿到templateId
        workOrderEntity.setTemplateId(paasFormEntityExt.getTemplateId());
        workOrderEntity.setMenuId(paasFormEntityExt.getMenuId());
        workOrderEntity.setCreatorId(formDataAddDTO.getUserId());
        //不走工作流，保存
        workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());
        return workOrderEntity;
    }

    @Override
    public BeforeSaveVO startWorkflowOrProcess(WorkOrderEntity workOrderEntity, WorkOrderFormEntityExt workOrderFormEntityExt, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo, FormDataAddDTO formDataAddDTO, Map<String, FieldAttrEntity> explainMap, List<FieldAttrEntity> explainList) throws XbbException {
        BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
        beforeSaveVO.setExplainMap(explainMap);
        beforeSaveVO.setExplainList(explainList);
        beforeSaveVO.setSaasNeedRedundantAttrPojo(saasNeedRedundantAttrPojo);
        beforeSaveVO.setWorkOrderFormEntityExt(workOrderFormEntityExt);
        beforeSaveVO.setWorkOrderEntity(workOrderEntity);

        //是否启用新工作流
        if (isEnableNewWorkflow(formDataAddDTO, beforeSaveVO, workOrderEntity)) {
            if (!formDataAddDTO.getIsSatisfyTrigger()) {
                // 无需走工作流
                beforeSaveVO.getWorkOrderEntity().setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            }
            return beforeSaveVO;
        }

        Integer noApprovalRequired = startProcess(workOrderFormEntityExt, formDataAddDTO, formDataAddDTO.getUserId(), workOrderEntity);

        beforeSaveVO.setNoApprovalRequired(noApprovalRequired);
        return beforeSaveVO;
    }

    @Override
    public BeforeSaveVO startWorkFlow(WorkOrderEntity workOrderEntity, WorkOrderFormEntityExt workOrderFormEntityExt, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo, FormDataAddDTO formDataAddDTO, Map<String, FieldAttrEntity> explainMap, List<FieldAttrEntity> explainList) throws XbbException {
        BeforeSaveVO beforeSaveVO = new BeforeSaveVO(explainMap, explainList, saasNeedRedundantAttrPojo, 1, workOrderFormEntityExt, workOrderEntity);

        //是否启用新工作流
        if (isEnableNewWorkflow(formDataAddDTO, beforeSaveVO, workOrderEntity)) {
            if (!formDataAddDTO.getIsSatisfyTrigger()) {
                // 无需走工作流
                beforeSaveVO.getWorkOrderEntity().setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            }
        }
        return beforeSaveVO;
    }

    @Override
    public void saveRollBack(Long dataId, String corpid, Integer saasMark, Integer businessType) throws XbbException {
        try {
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_WORK_ORDER;
            //删除主表es数据
            physicalDeleteFormData(dataId, corpid, indexTypeEnum);
            // 子表单的删除
            List<WorkOrderSubDataEntity> bomBillSubDataEntities = workOrderSubDataModel.getByDataId(dataId, corpid);
            if (CollectionsUtil.isNotEmpty(bomBillSubDataEntities)) {
                physicalDeleteSubBatch(corpid, bomBillSubDataEntities, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.impl.WorkOrderDataFormDataServiceImpl.saveRollBack 回滚失败：", e);
        }
    }

    @Override
    public void afterSaveRollBack(WorkOrderEntity newPaasFormDataEntity, Long dataId, String corpid, Integer saasMark, Integer businessType, ReRollBackEntity reRollBackEntity) throws XbbException {
        try {
            if (dataId == null || dataId == 0 || corpid == null || saasMark == null) {
                return ;
            }
            // 主业务以及子表单数据删除
            saveRollBack(dataId, corpid, saasMark, businessType);
            // 主业关联数据删除（如团队）
            // 关联新建业务数据删除
            // 关联新建业务数据子表单数据删除
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.impl.WorkOrderDataFormDataServiceImpl.afterSaveRollBack 回滚失败：", e);
        }

    }
}
